<?php
class FileModel extends BaseModel
{
    public function __construct()
    {
        parent::__construct();
    }

    public function add($file)
    {
        $file_limit = ConfLib::get('limit', 'file');
        if($file['size'] > $file_limit['max_size']) {
            throw new ModelException();
        }
        $tmp = explode('.', $file['name']);
        $file_ext = '';
        if((count($tmp)<2) || (!in_array($tmp[count($tmp)-1], $file_limit['ext']))) { //linux 下经常无后缀名
            throw new ModelException();
        }
        $file_ext = $tmp[count($tmp)-1];
        $file_id = md5_file($file['tmp_name']);
        switch($file_ext) {
            case 'torrent' :
                $bt = new BtLib($file['tmp_name']);
                $data = array(
                    'id' => $file_id,
                    'info_hash' => pack('H*', $bt->hash_info()), //string 转binary
                    'files' => json_encode($bt->content()),
                );
                $torrent_db = new TorrentDb();
                try {
                    $torrent_db->insertRow($data);
                } catch (Exception $e) {
                    //todo 已存在
                }
                break;
        }

        $filename = $file_id . '.' . $file_ext;

        $new_dir = ConfLib::get('file', 'stable_dir');
        $r = move_uploaded_file($file['tmp_name'], $new_dir . $filename);
        if($r === false) {
            throw new ModelException();
        }
        return $filename;
    }

    public function getProviders()
    {
        $provider_db = new ProviderDb();
        return $provider_db->selectRows();
    }


    public function update($data)
    {
        $where = array(
            'id' => $data['id'],
        );
        $this->movie_db->update($data, $where);
        return $id;
    }
}
?>
